package cn.starlightsoftware.sherly.controller.admin.file;

import cn.starlightsoftware.sherly.controller.admin.file.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import cn.starlightsoftware.sherly.model.Result;
import cn.starlightsoftware.sherly.service.file.FileService;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import static cn.starlightsoftware.sherly.model.Result.success;

/**
 * @author 谷子毅
 */
@Validated
@Tag(name = "admin-文件")
@RestController
@RequestMapping("/infra/file")
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    @Operation(summary = "文件上传", description = "后端中转上传")
    public Result<FileUploadRespVO> upload(FileUploadReqVO reqVO) {
        return success(fileService.upload(reqVO.getFile(), reqVO.getPath()));
    }

    @GetMapping("/download")
    @Operation(summary = "文件下载")
    public void download(@ParameterObject FileDownloadReqVO reqVO, HttpServletResponse response) {
        fileService.download(reqVO, response);
    }

    @GetMapping("/preSigned")
    @Operation(summary = "文件上传预签名", description = "前端直传：用于生成上传文件时需要的预签名")
    public Result<FilePreSignedRespVO> preSigned(@ParameterObject FilePreSignedReqVO reqVO) {
        return success(fileService.preSigned(reqVO));
    }

    @PostMapping("/record")
    @Operation(summary = "文件上传记录", description = "前端直传：上传完后使用该接口记录上传的文件")
    public Result<FileRecordRespVO> record(@RequestBody FileRecordReqVO reqVO) {
        return success(new FileRecordRespVO()
                .setFileId(fileService.record(reqVO))
        );
    }

    @PostMapping("/access")
    @Operation(summary = "文件访问", description = "前端直传：用于获取文件访问URL")
    public Result<FileAccessRespVO> access(@RequestBody FileAccessReqVO reqVO) {
        return success(new FileAccessRespVO()
                .setAccessUrls(fileService.access(reqVO.getFileIds()))
        );
    }

}
